<?php

/*
Plugin Name: Wok-Imager
Plugin URI: http://whatwebwhat.com/
Description: Wok-Imager makes sure that all your images fit the image tag.  You can also supply optional filters to modify the image.
Version: 1.0.0
Author: Marc Worrell
Author URI: http://whatwebwhat.com/
*/

/*
 * The MIT License
 * 
 * Copyright (c) 2008 Marc Worrell
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

function wok_imager_ob ( $s )
{
	if (	strpos($s, '<html') !== false
		&&	strpos($s, '<img') !== false)
	{
		// Fetch all the src files
		$ms = array();
		if (preg_match_all('|<img.*src=[\'"](.*)[\'"].*/>|isU', $s, $ms, PREG_OFFSET_CAPTURE|PREG_SET_ORDER))
		{
			$home      = get_bloginfo('home');
			$home_path = false;
			$resize    = array();

			foreach ($ms as $m)
			{
				$img_element = $m[0][0];
				$img_offset  = $m[0][1];
				$src_uri     = rawurldecode($m[1][0]);
				
				// This is a resize candidate iff:
				// - the file is local to this server
				// - there is a width, height or filter attribute
				if (	strpos($img_element, 'width=')
					||	strpos($img_element, 'height=')
					||	strpos($img_element, 'filter='))
				{
					// Only do our mapping stuff iff the image is a local file
					if (	!empty($src_uri)
						&&	($src_uri{0} == '/' || strncmp($src_uri, $home, strlen($home)) == 0)
						&&	strpos('?', $src_uri) === false
						&&	strpos('.php', $src_uri) === false)
					{
						// TODO: make fully qualified file path from the src_uri, test if it is a file
						if ($src_uri{0} != '/')
						{
							$file = str_replace('//', '/', ABSPATH . substr($src_uri, strlen($home)));
						}
						else
						{
							if ($home_path === false)
							{
								$home_path = parse_url($home, PHP_URL_PATH);
							}
							if (strncmp($home_path, $src_uri, strlen($home_path)))
							{
								$file = false;
							}
							else
							{
								$file = str_replace('//', '/', ABSPATH . substr($src_uri, strlen($home_path)));
							}
						}

						if ($file && is_file($file))
						{
							$resize[$img_offset] = array($img_element, $src_uri, $file);
						}
					}
				}
			}
			
			// Replace all resizable image tags with a reference to the resized image
			if (!empty($resize))
			{
				require_once dirname(__FILE__).'/wok-imager-resize.php';
				
				krsort($resize);
				$check_modified = get_option('wok_imager_check_modified');
				foreach ($resize as $offset => $r)
				{
					$img_element = wok_imager_resize($r[0], $r[1], $r[2], $home, $check_modified);
					if (strcmp($img_element,$r[0]))
					{
						$s = substr_replace($s, $img_element, $offset, strlen($r[0]));
					}
				}
			}
		}
	}
	return $s;
}


function wok_imager_start () 
{
	ob_start('wok_imager_ob');
}


function wok_imager_config_page () 
{
	if (function_exists('add_options_page'))
	{
		add_options_page('Wok-Imager', 'Wok-Imager', 'manage_options', 'wok-imager', 'wok_imager_conf');
	}
}

function wok_imager_conf()
{
	global $wok_imager_nonce;

	if (!empty($_POST)) 
	{
		if (function_exists('current_user_can') && !current_user_can('manage_options'))
		{
			die(__('Cheatin&#8217; uh?'));
		}

		update_option('wok_imager_check_modified', !empty($_POST['check_modified']) ? 1 : 0);

		if (!empty($_POST['clear_cache']))
		{
			// Recursively clear all cached images
			wok_imager_clear_cache();
			?>
			<div id="message" class="updated fade"><p><strong>Cleared cache. Options saved.</strong></p></div>
			<?php
		}
		else
		{
			?>
			<div id="message" class="updated fade"><p><strong>Options saved.</strong></p></div>
			<?php
		}
	}

	?>
	<form action="" method="post" id="wok-imager-conf">
	<?php wok_imager_nonce_field($wok_imager_nonce); ?>
	<div class="wrap">
		<h2><?php _e('Wok-Imager Configuration'); ?></h2>

		<p>
			Wok-Imager makes sure that all your images fit the image tag.  You can also supply optional filters to modify the image.
			The resized or filtered images are stored for later reuse.  When you change or delete an image then you might want to
			delete the cached files.
		</p>

		<table class="form-table">
			<tr>
				<th scope="row" colspan="2" class="th-full">
					<label for="check_modified">
						<input name="check_modified" type="checkbox" id="check_modified" value="1"  <?php if (get_option('wok_imager_check_modified')) echo 'checked="checked"'; ?> />
						Check modification time of images (slower)?
					</label>
				</th>
			</tr>
		</table>

		<p class="submit">
			<input type="submit" name="submit" value="<?php _e('Save Changes'); ?>" />
			<input type="submit" name="clear_cache" value="<?php _e('Clear Cache'); ?>" />
		</p>
	
	</div>
	</form>
	<?php
}

if ( !function_exists('wp_nonce_field') ) {
	function wok_imager_nonce_field($action = -1) { return; }
	$wok_imager_nonce = -1;
} else {
	function wok_imager_nonce_field($action = -1) { return wp_nonce_field($action); }
	$wok_imager_nonce = 'wok-imager-update-key';
}


function wok_imager_clear_cache ()
{
	wok_imager_unlink_recursive(ABSPATH . 'wp-content/uploads/wok-imager/');
}

function wok_imager_unlink_recursive ( $path )
{
	$path = realpath($path);
	if (!empty($path))
	{
	    if (is_dir($path) && !is_link($path))
	    {
			$dh = opendir($path);
	        if ($dh)
	        {
	            while (($sf = readdir($dh)) !== false)
	            {
	                if ($sf != '.' && $sf != '..')
	                {
	               		wok_imager_unlink_recursive($path.'/'.$sf);
	                }
	            }
	            closedir($dh);
	        }
			return rmdir($path);
	    }
		else
		{
			unlink($path);
		}
	}
}

add_action('admin_menu', 		'wok_imager_config_page');
add_action('template_redirect', 'wok_imager_start');

/* vi:set ts=4 sts=4 sw=4 binary noeol: */

?>